/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.github.florent37.camerafragment.internal.ui.view;

import ohos.agp.components.Component;
import ohos.agp.graphics.SurfaceOps;
import ohos.app.Context;

/**
 * 自动SurfaceView
 *
 * @since 2021-04-10
 */
public class AutoFitSurfaceView extends TempSurfaceView implements Component.EstimateSizeListener {
    private static final int TEMP_WIDTH = 1440;
    private static final int TEMP_HEIGHT = 1080;
    private SurfaceOps surfaceHolder;
    private int ratioWidth;
    private int ratioHeight;

    /**
     * 构造参数
     *
     * @param context 上下文
     * @param callback surface回调
     */
    public AutoFitSurfaceView(Context context, SurfaceOps.Callback callback) {
        super(context);
        this.surfaceHolder = getHolder();
        this.surfaceHolder.addCallback(callback);
        setEstimateSizeListener(this);
    }

    /**
     * 改变图形宽高比
     *
     * @param width Relative horizontal size
     * @param height Relative vertical size
     */
    public void setAspectRatio(int width, int height) {
        if (width < 0 || height < 0) {
            ratioWidth = TEMP_WIDTH;
            ratioHeight = TEMP_HEIGHT;
        }
        ratioWidth = width;
        ratioHeight = height;
        postLayout();
    }

    public int getRatioWidth() {
        return ratioWidth;
    }

    public int getRatioHeight() {
        return ratioHeight;
    }

    @Override
    public boolean onEstimateSize(int widthEstimatedConfig, int heightEstimatedConfig) {
        final int width = EstimateSpec.getSize(widthEstimatedConfig);
        final int height = EstimateSpec.getSize(heightEstimatedConfig);

        if (ratioWidth == 0 || ratioHeight == 0) {
            setEstimatedSize(width, height);
        } else {
            if (width < height * (ratioWidth / (float) ratioHeight)) {
                setEstimatedSize(width, (int) (width * (ratioWidth / (float) ratioHeight)));
            } else {
                setEstimatedSize((int) (height * (ratioWidth / (float) ratioHeight)), height);
            }
        }
        return true;
    }
}
